package com.itclj.common.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.itclj.common.exception.LogicException;

/**
 * 鉴权处理
 * 
 * @author lujun.chen
 * @version 2016年11月18日
 * @since JDK1.8
 */
public class AuthUtil {

	private static Map<String, String> params = new HashMap<String, String>();

	/**
	 * 检查用户名密码是否合法
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return true 合法
	 */
	public static Boolean check(String username, String password) {
		String check = PropertyUtil.getValue("file.auth.check");
		if ("true".equals(check)) {
			initParam();
			if (StringUtils.isBlank(username)) {
				throw new LogicException(LogicException.ErrorNumber.SYSERROR, "用户名不能为空");
			}
			if (StringUtils.isBlank(password)) {
				throw new LogicException(LogicException.ErrorNumber.SYSERROR, "密码不能为空");
			}
			if (!params.containsKey(username)) {
				throw new LogicException(LogicException.ErrorNumber.SYSERROR, "用户名错误");
			}
			if (!password.equals(params.get(username))) {
				throw new LogicException(LogicException.ErrorNumber.SYSERROR, "密码错误");
			}
		}
		return true;
	}

	public static void initParam() {
		String usernames = PropertyUtil.getValue("file.auth.username");
		String passwords = PropertyUtil.getValue("file.auth.password");
		String[] usernameArr = StringUtils.split(usernames, " ");
		String[] passwordArr = StringUtils.split(passwords, " ");
		if (usernameArr.length != passwordArr.length) {
			throw new LogicException(LogicException.ErrorNumber.SYSERROR, "系统设置的用户名和密码个数不匹配");
		}
		for (int n = 0; n < usernameArr.length; n++) {
			params.put(usernameArr[n], passwordArr[n]);
		}
	}

}
